<template>
  <view class="container" v-if="article">
    <!-- 文章封面图轮播 -->
    <swiper class="cover-swiper" indicator-dots="true" autoplay="true">
      <swiper-item v-for="(image, index) in article.articleImagesList || []" :key="index">
        <image :src="image.imageUrl" mode="aspectFill" class="cover"></image>
      </swiper-item>
    </swiper>
    
    <!-- 场所信息头部 -->
    <view class="place-header">
      <view class="place-title">
        <text class="name">{{article.title}}</text>
        <text class="score" v-if="article.score">{{article.score}}分</text>
      </view>
      <view class="place-info">
        <text>{{article.viewCount || 0}}人去过</text>
        <text class="separator">|</text>
        <text>{{article.category || '景点'}}</text>
        <text class="separator">|</text>
        <text>{{article.location || '暂无位置信息'}}</text>
      </view>
      <view class="place-address" @tap="openMap">
        <text>{{article.address || '暂无详细地址'}}</text>
        <text class="map-icon">地图 ></text>
      </view>
    </view>
    
    <!-- 开放信息和门票 -->
    <view class="ticket-section">
      <view class="open-info">
        <view class="left">
          <view class="status">开放中</view>
          <view class="time">{{article.openTime || '09:00-17:00 开放'}}</view>
        </view>
        <view class="right" @tap="navigateToMap">
          <image class="map-pin" src="/static/images/map-pin.png" mode="aspectFit"></image>
          <text>导航</text>
        </view>
      </view>
      
      <!-- 门票信息 -->
      <view class="ticket-info">
        <view class="ticket-header">
          <text class="title">门票</text>
          <text class="subtitle">预订可选日期</text>
        </view>
        
        <view class="ticket-item">
          <view class="ticket-name">{{article.title}}门票 - 成人票</view>
          <view class="ticket-price">¥{{article.ticketPrice || 40}}</view>
          <button class="book-btn">立即预订</button>
        </view>
        
        <view class="ticket-item">
          <view class="ticket-name">{{article.title}}门票 - 学生票</view>
          <view class="ticket-price">¥{{article.studentPrice || 20}}</view>
          <button class="book-btn">立即预订</button>
        </view>
      </view>
    </view>
    
    <!-- 文章内容 -->
    <view class="content-section">
      <view class="section-title">介绍</view>
      <view class="article-content">
        <rich-text :nodes="article.content"></rich-text>
      </view>
      
      <!-- 作者信息 -->
      <view class="author" v-if="article.user">
        <image class="avatar" :src="article.user.avatarUrl" mode="aspectFill"></image>
        <view class="info">
          <view class="name">{{article.user.nickname}}</view>
          <view class="meta">
            <text>{{formatDate(article.createdAt)}}</text>
            <text>阅读 {{article.views}}</text>
          </view>
        </view>
        <button class="follow-btn">关注</button>
      </view>
    </view>
    
    <!-- 评论区 -->
    <view class="comments-section" v-if="article.articleCommentsList && article.articleCommentsList.length">
      <view class="section-title">评论 <text class="comment-count">({{article.articleCommentsList.length}})</text></view>
      <view class="comments-list">
        <view class="comment-item" v-for="(comment, index) in article.articleCommentsList" :key="comment.commentId">
          <image class="comment-avatar" :src="getUserAvatar(comment.userId)" mode="aspectFill"></image>
          <view class="comment-content">
            <view class="comment-user">{{getUserName(comment.userId)}}</view>
            <view class="comment-date">{{formatDate(comment.createdAt)}} 来自{{comment.source || '北京'}}</view>
            <view class="comment-text">{{comment.comment}}</view>
            <view class="comment-meta">
              <view class="comment-like" @tap="likeComment(comment)">
                <text class="iconfont icon-like"></text>
                <text>{{comment.likes}}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <view class="view-all-comments" @tap="viewAllComments">
        <text>查看全部{{article.commentCount || 0}}条评论 ></text>
      </view>
    </view>
    
    <!-- 达人游记 -->
    <view class="travel-notes">
      <view class="section-title">达人游记</view>
      <view class="notes-list">
        <scroll-view class="notes-scroll" scroll-x>
          <view class="note-item" v-for="(index) in 4" :key="index" @tap="goToRelatedArticle(index)">
            <image class="note-image" :src="getRandomImage()" mode="aspectFill"></image>
            <view class="note-title">{{getRandomTitle()}}</view>
            <view class="note-author">
              <image class="note-avatar" src="/static/images/avatar.gif" mode="aspectFill"></image>
              <text>{{getRandomName()}}</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    
    <!-- 互动栏 -->
    <view class="interaction-bar">
      <view class="write-comment">
        <text>写评论...</text>
      </view>
      <view class="action-group">
        <view class="action">
          <text class="iconfont icon-like"></text>
          <text>{{article.likes}}</text>
        </view>
        <view class="action">
          <text class="iconfont icon-collect"></text>
          <text>收藏</text>
        </view>
        <view class="action">
          <text class="iconfont icon-share"></text>
          <text>分享</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import request from '@/utils/request'

export default {
  data() {
    return {
      article: null,
      userMap: {}, // 用于存储用户信息的映射
      randomTitles: [
        '别再踩踏故宫了，去过100次的土著攻略',
        '故宫必须攻略！感受文化的深厚底蕴',
        '去故宫，一定要带的十件事',
        '北京故宫必游攻略！博物馆文化的深度欣赏'
      ],
      randomNames: ['小小在北京', '旅行家10...', '京城攻略', '文化探索者'],
      randomImages: [
        'http://101.37.17.240:9000/shzy/故宫1.jpg',
        'http://101.37.17.240:9000/shzy/故宫2.jpg',
        'http://101.37.17.240:9000/shzy/故宫3.jpg',
        'http://101.37.17.240:9000/shzy/故宫4.jpg'
      ]
    }
  },
  onLoad(options) {
    // 获取文章ID
    const articleId = options.id;
    
    if (!articleId) {
      uni.showToast({
        title: '缺少文章ID',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    }
    
    // 从缓存中获取文章数据
    const cachedArticle = uni.getStorageSync('currentArticle');
    
    if (cachedArticle && cachedArticle.articleId == articleId) {
      this.article = cachedArticle;
      
      // 构建用户映射，方便评论区使用
      if (this.article.user) {
        this.userMap[this.article.user.userId] = this.article.user;
      }
      
      // 补充其他用户信息（如评论用户）
      this.loadCommentUsers();
    } else {
      // 如果缓存中没有，则通过API获取
      this.getArticleDetail(articleId);
    }
  },
  methods: {
    getArticleDetail(articleId) {
      // 显示加载状态
      uni.showLoading({
        title: '加载中...'
      });
      
      // 调用实际的API接口获取文章详情
      request.article.get('/api/article/getArticleDetail', { articleId })
        .then(res => {
          if (res.code === 200 && res.data) {
            this.article = res.data;
            
            // 构建用户映射
            if (this.article.user) {
              this.userMap[this.article.user.userId] = this.article.user;
            }
            
            // 补充其他用户信息（如评论用户）
            this.loadCommentUsers();
          } else {
            uni.showToast({
              title: res.errorMessage || '获取文章详情失败',
              icon: 'none'
            });
          }
        })
        .catch(err => {
          console.error('获取文章详情失败:', err);
          uni.showToast({
            title: '获取文章详情失败',
            icon: 'none'
          });
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    
    loadCommentUsers() {
      // 如果有评论，获取评论中的用户信息
      if (this.article.articleCommentsList && this.article.articleCommentsList.length > 0) {
        // 获取所有评论中的用户ID
        const userIds = [...new Set(this.article.articleCommentsList.map(comment => comment.userId))];
        // 过滤掉已有的用户ID
        const newUserIds = userIds.filter(id => !this.userMap[id]);
        
        if (newUserIds.length > 0) {
          // 获取用户信息
          request.article.get('/api/user/getUserInfo', { userIds: newUserIds.join(',') })
            .then(res => {
              if (res.code === 200 && res.data) {
                const users = Array.isArray(res.data) ? res.data : [res.data];
                users.forEach(user => {
                  this.userMap[user.userId] = user;
                });
              }
            })
            .catch(err => {
              console.error('获取评论用户信息失败:', err);
            });
        }
      }
    },
    
    formatDate(dateString) {
      if (!dateString) return '';
      
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    
    getUserAvatar(userId) {
      return (this.userMap[userId] && this.userMap[userId].avatarUrl) || '/static/images/avatar.gif';
    },
    
    getUserName(userId) {
      return (this.userMap[userId] && this.userMap[userId].nickname) || '游客';
    },
    
    openMap() {
      // 打开地图页面
      uni.navigateTo({
        url: '/pages/map/index?location=' + encodeURIComponent(this.article.location || '北京故宫博物院')
      });
    },
    
    navigateToMap() {
      // 使用内置地图导航
      const address = this.article.address || '北京市东城区景山前街4号';
      uni.openLocation({
        latitude: this.article.latitude || 39.9163,
        longitude: this.article.longitude || 116.3972,
        name: this.article.title,
        address: address,
        scale: 18,
        success: function() {
          console.log('导航打开成功');
        },
        fail: function(err) {
          console.error('导航打开失败:', err);
          uni.showToast({
            title: '导航打开失败，请稍后再试',
            icon: 'none'
          });
        }
      });
    },
    
    likeComment(comment) {
      // 点赞评论
      uni.showToast({
        title: '点赞成功',
        icon: 'success'
      });
      comment.likes++; // 模拟点赞效果
    },
    
    viewAllComments() {
      // 查看全部评论
      uni.navigateTo({
        url: `/pages/comment/list?articleId=${this.article.articleId}`
      });
    },
    
    goToRelatedArticle(index) {
      // 跳转到相关文章
      uni.showToast({
        title: '即将打开相关游记',
        icon: 'none'
      });
    },
    
    getRandomTitle() {
      const index = Math.floor(Math.random() * this.randomTitles.length);
      return this.randomTitles[index];
    },
    
    getRandomName() {
      const index = Math.floor(Math.random() * this.randomNames.length);
      return this.randomNames[index];
    },
    
    getRandomImage() {
      const index = Math.floor(Math.random() * this.randomImages.length);
      return this.randomImages[index];
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f8f8f8;
}

.cover-swiper {
  width: 100%;
  height: 500rpx;
}

.cover {
  width: 100%;
  height: 100%;
}

.place-header {
  background: #fff;
  padding: 30rpx;
  
  .place-title {
    display: flex;
    align-items: center;
    margin-bottom: 15rpx;
    
    .name {
      font-size: 40rpx;
      font-weight: bold;
      color: #333;
      margin-right: 20rpx;
    }
    
    .score {
      font-size: 32rpx;
      color: #FF9500;
      font-weight: bold;
    }
  }
  
  .place-info {
    font-size: 24rpx;
    color: #999;
    margin-bottom: 15rpx;
    
    .separator {
      margin: 0 10rpx;
    }
  }
  
  .place-address {
    display: flex;
    justify-content: space-between;
    font-size: 26rpx;
    color: #666;
    
    .map-icon {
      color: #4080ff;
    }
  }
}

.ticket-section {
  margin-top: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  
  .open-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    border-bottom: 1px solid #f0f0f0;
    
    .left {
      .status {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 6rpx;
      }
      
      .time {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .right {
      display: flex;
      align-items: center;
      color: #4080ff;
      font-size: 26rpx;
      
      .map-pin {
        width: 32rpx;
        height: 32rpx;
        margin-right: 6rpx;
      }
    }
  }
  
  .ticket-info {
    padding: 20rpx 30rpx 30rpx;
    
    .ticket-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .subtitle {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .ticket-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      
      .ticket-name {
        font-size: 28rpx;
        color: #333;
        flex: 2;
      }
      
      .ticket-price {
        font-size: 30rpx;
        color: #ff0000;
        font-weight: bold;
        flex: 1;
        text-align: center;
      }
      
      .book-btn {
        width: 160rpx;
        height: 60rpx;
        line-height: 60rpx;
        background: #4080ff;
        color: #fff;
        font-size: 26rpx;
        border-radius: 30rpx;
        padding: 0;
        margin: 0;
      }
    }
  }
}

.content-section {
  margin-top: 20rpx;
  padding: 30rpx;
  background: #fff;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    border-left: 6rpx solid #4080ff;
    padding-left: 20rpx;
  }
  
  .article-content {
    font-size: 30rpx;
    line-height: 1.8;
    color: #333;
    margin-bottom: 30rpx;
  }
  
  .author {
    display: flex;
    align-items: center;
    margin-top: 30rpx;
    padding-top: 30rpx;
    border-top: 1px solid #f0f0f0;
    
    .avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin-right: 20rpx;
    }
    
    .info {
      flex: 1;
      
      .name {
        font-size: 30rpx;
        color: #333;
        margin-bottom: 6rpx;
      }
      
      .meta {
        font-size: 24rpx;
        color: #999;
        
        text {
          margin-right: 20rpx;
        }
      }
    }
    
    .follow-btn {
      width: 120rpx;
      height: 56rpx;
      line-height: 56rpx;
      text-align: center;
      background: #4080ff;
      color: #fff;
      font-size: 28rpx;
      border-radius: 28rpx;
      padding: 0;
      margin: 0;
    }
  }
}

.comments-section {
  margin-top: 20rpx;
  padding: 30rpx;
  background: #fff;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
    border-left: 6rpx solid #4080ff;
    padding-left: 20rpx;
    
    .comment-count {
      font-weight: normal;
      color: #999;
    }
  }
  
  .comments-list {
    .comment-item {
      display: flex;
      margin-bottom: 30rpx;
      
      .comment-avatar {
        width: 70rpx;
        height: 70rpx;
        border-radius: 50%;
        margin-right: 20rpx;
      }
      
      .comment-content {
        flex: 1;
        
        .comment-user {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 4rpx;
          font-weight: bold;
        }
        
        .comment-date {
          font-size: 22rpx;
          color: #999;
          margin-bottom: 8rpx;
        }
        
        .comment-text {
          font-size: 28rpx;
          color: #333;
          line-height: 1.5;
          margin-bottom: 10rpx;
        }
        
        .comment-meta {
          display: flex;
          justify-content: flex-end;
          font-size: 24rpx;
          color: #999;
          
          .comment-like {
            display: flex;
            align-items: center;
            
            .iconfont {
              font-size: 24rpx;
              margin-right: 6rpx;
            }
          }
        }
      }
    }
  }
  
  .view-all-comments {
    text-align: center;
    padding: 20rpx 0 0;
    font-size: 26rpx;
    color: #4080ff;
  }
}

.travel-notes {
  margin-top: 20rpx;
  padding: 30rpx;
  background: #fff;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
    border-left: 6rpx solid #4080ff;
    padding-left: 20rpx;
  }
  
  .notes-scroll {
    white-space: nowrap;
  }
  
  .notes-list {
    .note-item {
      display: inline-block;
      width: 280rpx;
      margin-right: 20rpx;
      border-radius: 12rpx;
      overflow: hidden;
      
      .note-image {
        width: 280rpx;
        height: 180rpx;
        border-radius: 12rpx 12rpx 0 0;
      }
      
      .note-title {
        font-size: 26rpx;
        color: #333;
        padding: 10rpx 10rpx 6rpx;
        white-space: normal;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        height: 80rpx;
        line-height: 1.3;
      }
      
      .note-author {
        display: flex;
        align-items: center;
        padding: 0 10rpx 10rpx;
        
        .note-avatar {
          width: 36rpx;
          height: 36rpx;
          border-radius: 50%;
          margin-right: 8rpx;
        }
        
        text {
          font-size: 22rpx;
          color: #999;
        }
      }
    }
  }
}

.interaction-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  
  .write-comment {
    flex: 1;
    height: 60rpx;
    line-height: 60rpx;
    background: #f5f5f5;
    border-radius: 30rpx;
    padding: 0 20rpx;
    font-size: 26rpx;
    color: #999;
  }
  
  .action-group {
    display: flex;
    margin-left: 20rpx;
    
    .action {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-left: 30rpx;
      
      .iconfont {
        font-size: 40rpx;
        color: #666;
      }
      
      text {
        font-size: 22rpx;
        color: #666;
      }
    }
  }
}
</style> 